<!--
  进件详细信息的入口页面（包含 ： 保存草稿， 发起进件）

  @author terrfly
  @site https://www.jeequan.com
  @date 2022/05/07 10:20
-->

<template>
  <a-card class="table-card">
    <slot name="top">
      <!-- 吸顶： 返回列表 / 智能读取 / 保存草稿 按钮项 -->
      <a-affix offsetTop="0">
        <div style="display: flex; justify-content: space-between; line-height: 60px; background-color: white;">
          <a-button style="line-height: 60px;" type="text" @click="emits('switchApplyPage', 'list')"><left-outlined />返回列表页</a-button>
          <div style="font-weight: bold; margin-left: 30px;"> {{ isView ? '查看进件信息' : '填写进件资料' }}</div>
          <div style="width: 400px; display: flex; align-items: center; justify-content:space-evenly">
            <a-button v-if="!isView" @click="showMobileQrcode"><qrcode-outlined />手机扫码填写</a-button>

            <a-button v-if="!isView" @click="mergeApplyDetailInfosFunc('')"><bulb-outlined />智能读取</a-button>
            <a-tooltip v-if="!isView" placement="left" title="保存草稿将不验证数据的合法性">
              <a-button type="primary " @click="saveDataFunc(true)"><save-outlined />  保存草稿 </a-button>
            </a-tooltip>
          </div>
        </div>
        <a-divider style="margin: 0" />
      </a-affix>
    </slot>
    <a-card v-if="mchApplymentData.state == 3" style="width: 90%;margin: 15px 0px 15px 20px; padding: 12px; background-color: #fff1f0;">
      <a-row type="flex" style="color: red;">
        <a-col flex="auto"><exclamation-circle-outlined /> {{ mchApplymentData.applyErrorInfo }}</a-col>
      </a-row>
    </a-card>

    <!-- 引入具体的接口组件  -->
    <component :is="vdata.currentComponent" ref="ifCodeComponentRef" />

    <slot name="bottom">
      <!-- 底部操作项 -->
      <a-affix v-if="!isView" :offset-bottom="20">
        <div style="background-color: white;">
          <a-divider style="margin: 0; margin-top: 20px;" />

          <div class="bottom-buttons">
            <div class="bottom-buttons-item" @click="emits('switchApplyPage', 'list')">
              <a-button type="link" style="color: #808080 ;"><left-outlined />返回列表页</a-button>
            </div>
            <div style="width: 1px; height: 100%; background-color: #f0f0f0;" />
            <div class="bottom-buttons-item" @click="saveDataFunc(false)">
              <a-button type="link">发起进件<send-outlined /></a-button>
            </div>
          </div>
        </div>
      </a-affix>
    </slot>
  </a-card>

  <a-modal v-model:visible="vdata.isShowMobileQr" title="手机扫码填写" :footer="null" :width="300">
    <div style="width:100%;margin-bottom:20px;text-align:center">
      <div id="qrCodeUrl" style="width: 300px" class="qrcode" />
      <QrcodeVue :value="vdata.mobileQrUrl" :size="250" class="qrcode" />
      <br>
      <p style="color:red">为避免信息泄露，请当前系统登录者扫码！ 不要将二维码发送给他人！ </p>
    </div>
  </a-modal>
</template>
<script setup lang="ts">

import {ref, reactive, computed, getCurrentInstance, inject, defineEmits, nextTick, defineExpose, provide} from 'vue'
import { API_URL_MCH_APPLYMENT_LIST, $getMergeApplyDetailInfos, reqLoad, $getIsvChannelConfig } from '@/api/manage'
import QrcodeVue from 'qrcode.vue'
import storage from '@/utils/jeepayStorageWrapper'
import { getOriginIfCode } from '../util/jeepayComponentUtil.js'


const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const ifCodeComponentRef = ref()

// list页面的 切换页面的函数
const emits = defineEmits(['switchApplyPage'])

// 当前页面的对象信息
const vdata : any = reactive({
  currentComponent: null,
  applymentDetailInfo: {}, //进件详细参数，JSON串

  isShowMobileQr: false,  // 是否显示手机扫码二维码
  mobileQrUrl: '' // 二维码地址

})

// 参数注入： 接收进件参数（包含 商户号， ifCode ）
let mchApplymentDataRef : any = inject('mchApplymentData')
let mchApplymentData : any = mchApplymentDataRef.value

// 参数注入： 是否预览模式
let isView : any = inject('isView')

// 参数注入： 是否手机端
let isMobile : any = inject('isMobile')

// 参数注入： 副本来源
let copyInfoSourceApplyId : any = inject('copyInfoSourceApplyId')


// 向子组件注入： 进件参数具体数据
provide('applymentDetailInfo', computed( ()=> vdata.applymentDetailInfo) )


// 智能读取
function mergeApplyDetailInfosFunc(fixApplyId){

  // 传入当前页面操作的 ifCode 到后台
  const ifCodeView = getOriginIfCode(mchApplymentData.ifCode)

  return $getMergeApplyDetailInfos(mchApplymentData.mchNo, fixApplyId, ifCodeView).then(res => {
    $infoBox.message.info('读取成功')
    Object.assign(vdata.applymentDetailInfo, res)
    if(ifCodeComponentRef.value.mergeApplyDetailInfosCallback){
      ifCodeComponentRef.value.mergeApplyDetailInfosCallback()
    }
  })
}

// 保存草稿的事件 
function saveDataFunc(isTemp){
  console.log(mchApplymentData)

  if(!ifCodeComponentRef.value.saveDataPreCallback){
    return Promise.reject()
  }

  // 调用子组件的回调函数
  return ifCodeComponentRef.value.saveDataPreCallback(isTemp).then(() => {
      
    // 参数复制
    let reqData = Object.assign({}, mchApplymentData)

    reqData.isTempData = isTemp

    reqData.mchFullName = vdata.applymentDetailInfo.mchFullName
    reqData.mchShortName = vdata.applymentDetailInfo.mchShortName
    reqData.merchantType = vdata.applymentDetailInfo.merchantType
    reqData.contactName = vdata.applymentDetailInfo.contactName
    reqData.contactPhone = vdata.applymentDetailInfo.contactPhone
    reqData.areaCode = vdata.applymentDetailInfo.areaCode ? vdata.applymentDetailInfo.areaCode[2] : null
    reqData.address = vdata.applymentDetailInfo.address

    //  替换paywayFeeList
    let applymentDetailInfoCopy = Object.assign({}, vdata.applymentDetailInfo)
    if(applymentDetailInfoCopy.reqPaywayFeeList){
      applymentDetailInfoCopy.paywayFeeList = applymentDetailInfoCopy.reqPaywayFeeList
    }

    delete applymentDetailInfoCopy.reqPaywayFeeList

    reqData.applyDetailInfo = JSON.stringify(applymentDetailInfoCopy)

    // 组装报文， 发送请求
    if(mchApplymentData.applyId){
      return reqLoad.updateById(API_URL_MCH_APPLYMENT_LIST, mchApplymentData.applyId, reqData).then( res => {
            return submitSuccess(isTemp)
      })
    }else{
      return reqLoad.add(API_URL_MCH_APPLYMENT_LIST, reqData).then( res => {
        return submitSuccess(isTemp)
      })
    }
  })
}

// 封装： 新增 or 修改保存 的响应事件 
function submitSuccess(isTempData){
    $infoBox.message.success(isTempData ? '保存成功' : '提交成功，请等待审核')
    
    // 返回列表
    emits('switchApplyPage', 'list')

    return Promise.resolve()
}

// 页面渲染函数
function pageRender(){

  // props.selectIfCode格式： ifCode或ifCode_1等等，保存数据使用传入的ifCode或ifCode_1，页面渲染使用ifCode(需截取ifCode_1)
  const ifCodeView = getOriginIfCode(mchApplymentData.ifCode)

  // 根据支付接口名称  动态引入组件 
  import(`./diy/${ifCodeView}/Applyment.vue`).then((module) => {
    vdata.currentComponent = module.default

    // 加载已存的数据
    if(mchApplymentData.applyDetailInfo){
      vdata.applymentDetailInfo = JSON.parse(mchApplymentData.applyDetailInfo)
    }

    // 服务商渠道参数配置
    $getIsvChannelConfig(mchApplymentData.mchNo, mchApplymentData.ifCode).then(res => {
      if (res) {
        Object.assign(vdata.applymentDetailInfo, res)
      }

    })

    // 副本来源 
    if(copyInfoSourceApplyId && copyInfoSourceApplyId.value){
      nextTick(() => {
        mergeApplyDetailInfosFunc(copyInfoSourceApplyId.value)
      })
    }

  })

}

// 显示手机扫码二维码地址二维码
function showMobileQrcode(){

  let url = ''

  let jeepayToken = storage.getToken()

  // 包含 记录ID
  if(mchApplymentData.applyId){
    url = `${window.location.origin}/h5MchApplyment?isView=${isView.value ? 1 : 0 }&jeepayToken=${jeepayToken}&applyId=${mchApplymentData.applyId}`
  }else{

    let copyInfoSourceApplyIdParam : any = ''
    // 副本来源 
    if(copyInfoSourceApplyId && copyInfoSourceApplyId.value){
      copyInfoSourceApplyIdParam =copyInfoSourceApplyId.value
    }
    
    url = `${window.location.origin}/h5MchApplyment?isView=${isView.value ? 1 : 0 }&jeepayToken=${jeepayToken}&mchNo=${mchApplymentData.mchNo}&ifCode=${mchApplymentData.ifCode}&copyInfoSourceApplyId=${copyInfoSourceApplyIdParam}`
  }

  vdata.mobileQrUrl = url

  console.log(url)

  vdata.isShowMobileQr = true
}

defineExpose({ pageRender, saveDataFunc, mergeApplyDetailInfosFunc })
</script>
<style  lang="less" scoped>

.bottom-buttons{
  display: flex; flex-direction: row; justify-content: center; height: 60px;

  .bottom-buttons-item{
    flex-grow: 1; display: flex; flex-direction: column; justify-content: center;
  }

   .bottom-buttons-item:hover{
    transition: 0.3s ease;
    background-color: rgba(23, 91, 230, 0.05);
    cursor: pointer;
  }

}

</style>
